<?php
/**
 * $Id$
 * 安装函数库
 */

if (!defined('IN_APP')) die('Hacking attempt!');

/**
 * 从sql文件安装数据
 */
function install_data($sql_files) {
	global $err;

	require_once ROOT_PATH . '/includes/config.php';
	require_once ROOT_PATH . '/lib/class.mysql.php';
	require_once ROOT_PATH . '/lib/cls_sql_exe.php';

	$db = MySQL::getInstance();
	$sql_exe = new sql_exe($db);
	$result = $sql_exe->run_all_file($sql_files);
	if ($result === false) {
		$err->add($se->error);
		return false;
	}
	return true;
}

/**
 * 获得GD版本号
 */
function get_gd_version() {
	require_once ROOT_PATH . '/includes/cls_image.php';
	return image::gd_version();
}

/**
 * 是否支持GD
 */
function has_supported_gd() {
	return get_gd_version() === 0 ? false : true;
}

/**
 * 获得系统的信息
 */
function get_system_info() {
	global $_LANG;
	$system_info = array();

	$system_info[] = array($_LANG['php_os'], PHP_OS);
	$system_info[] = array($_LANG['php_ver'], PHP_VERSION);

	/* 检查 MySQL支持情况*/
	$mysql_enabled = function_exists('mysql_connect') ? $_LANG['support'] : $_LANG['not_support'];
	$system_info[] = array($_LANG['does_support_mysql'], $mysql_enabled);

	/* 检查图片处理函数库*/
	$gd_ver = get_gd_version();
	$gd_ver = empty($gd_ver) ? $_LANG['not_support'] : $gd_ver;

	if ($gd_ver > 0) {
		if (PHP_VERSION >= '4.3' && function_exists('gd_info')) {
			$gd_info = gd_info();
			$jpeg_enabled = ($gd_info['JPEG Support']        === true) ? $_LANG['support'] : $_LANG['not_support'];
			$gif_enabled  = ($gd_info['GIF Create Support'] === true) ? $_LANG['support'] : $_LANG['not_support'];
			$png_enabled  = ($gd_info['PNG Support']        === true) ? '支持' : '不支持';
		} else {
			if (function_exists('imagetypes')) {
				$jpeg_enabled = ((imagetypes() & IMG_JPG) > 0) ? $_LANG['support'] : $_LANG['not_support'];
				$gif_enabled  = ((imagetypes() & IMG_GIF) > 0) ? $_LANG['support'] : $_LANG['not_support'];
				$png_enabled  = ((imagetypes() & IMG_PNG) > 0) ? $_LANG['support'] : $_LANG['not_support'];
			} else {
				$jpeg_enabled = $_LANG['not_support'];
				$gif_enabled  = $_LANG['not_support'];
				$png_enabled  = $_LANG['not_support'];
			}
		}
	} else {
		$jpeg_enabled = $_LANG['not_support'];
		$gif_enabled  = $_LANG['not_support'];
		$png_enabled  = $_LANG['not_support'];
	}
	$system_info[] = array($_LANG['gd_version'], $gd_ver);
	$system_info[] = array($_LANG['jpeg'], $jpeg_enabled);
	$system_info[] = array($_LANG['gif'],  $gif_enabled);
	$system_info[] = array($_LANG['png'],  $png_enabled);

	/* 服务器是否开启了安全模式*/
	$safe_mode = ini_get('safe_mode') == '1' ? $_LANG['safe_mode_on'] : $_LANG['safe_mode_off'];
	$system_info[] = array($_LANG['safe_mode'], $safe_mode);

	return $system_info;
}

/**
 * 获得数据库列表
 */
function get_db_list($db_host, $db_port, $db_user, $db_pass) {
	global $err, $_LANG;
	$databases = array();
	$filter_dbs = array('information_schema', 'mysql');
	$db_host = construct_db_host($db_host, $db_port);
	$conn = @mysql_connect($db_host, $db_user, $db_pass);

	if ($conn == false) {
		$err->add($_LANG['connect_failed']);
		return false;
	}
	keep_right_conn($conn);

	$result = mysql_query('SHOW DATABASES', $conn);
	if ($result !== false) {
		while (($row = mysql_fetch_assoc($result)) !== false) {
			if (in_array($row['Database'], $filter_dbs)) {
				continue;
			}
			$databases[] = $row['Database'];
		}
	} else {
		$err->add($_LANG['query_failed']);
		return false;
	}
	@mysql_close($conn);
	return $databases;
}

/**
 * 获得时区列表
 */
function get_timezone_list($lang) {
	if (file_exists(ROOT_PATH . '/install/data/inc_timezones_' . $lang . '.php')) {
		require_once ROOT_PATH . '/install/data/inc_timezones_' . $lang . '.php';
	} else {
		require_once ROOT_PATH . '/install/data/inc_timezones_zh_cn.php';
	}
	return array_unique($timezones);
}

/**
 * 获得服务器所在时区
 */
function get_local_timezone() {
	if (PHP_VERSION >= '5.1') {
		$local_timezone = date_default_timezone_get();
	} else {
		$local_timezone = '';
	}
	return $local_timezone;
}

/**
 * 创建指定名字的数据库
 */
function create_database($db_host, $db_port, $db_user, $db_pass, $db_name) {
	global $err, $_LANG;
	$db_host = construct_db_host($db_host, $db_port);
	$conn = @mysql_connect($db_host, $db_user, $db_pass);

	if ($conn === false) {
		$err->add($_LANG['connect_failed']);
		return false;
	}
	$mysql_version = mysql_get_server_info($conn);
	keep_right_conn($conn, $mysql_version);
	if (mysql_select_db($db_name, $conn) === false) {
		if ($mysql_version >= '4.1') {
			$sql = 'CREATE DATABASE ' . $db_name . ' DEFAULT CHARACTER SET utf8';
		} else {
			$sql = 'CREATE DATABASE ' . $db_name;
		}
		if (mysql_query($sql, $conn) === false) {
			$err->add($_LANG['cannt_create_database']);
			return false;
		}
	}
	@mysql_close($conn);
	return true;
}

/**
 * 保证正确的数据库连接
 */
function keep_right_conn($conn, $mysql_version = '') {
	if ($mysql_version == '') {
		$mysql_version = mysql_get_server_info($conn);
	}

	if ($mysql_version >= '4.1') {
		mysql_query('SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary', $conn);

		if ($mysql_version >= '5.0.1') {
			mysql_query('SET sql_mode=\'\'', $conn);
		}
	}
}

/**
 * 创建配置文件
 */
function create_config_file($db_host, $db_port, $db_user, $db_pass, $db_name, $prefix, $timezone) {
	global $err, $_LANG;
	$db_host = construct_db_host($db_host, $db_port);

	$content = '<?php' . "\n";
	$content .= '/* database*/' . "\n";
	$content .= 'define(\'DB_HOST\', \'' . $db_host . '\');' . "\n";
	$content .= 'define(\'DB_USER\', \'' . $db_user . '\');' . "\n";
	$content .= 'define(\'DB_PASSD\', \'' . $db_pass . '\');' . "\n";
	$content .= 'define(\'DB_NAME\', \'' . $db_name . '\');' . "\n";
	$content .= 'define(\'DB_PREFIX\', \'' . $prefix . '\');' . "\n";
	$content .= 'define(\'TIMEZONE\', \'' . $timezone . '\');' . "\n";

	$content .= '/* etc*/' . "\n";
	$content .= 'define(\'ADMIN_PERPAGE_NUM\', 15);' . "\n";
	$content .= 'define(\'AUTH_COOKIE_NAME\', \'EM_AUTHCOOKIE_VvQM1Kxc9DQ9wXO4QWATa881ih6nC7Gc\');' . "\n";

	$fp = @fopen(ROOT_PATH . '/data/config.php', 'wb+');
	if (!$fp) {
		$err->add($_LANG['open_config_file_failed']);
		return false;
	}
	/* 写入配置文件*/
	if (!@fwrite($fp, trim($content))) {
		$err->add($_LANG['write_config_file_failed']);
		return false;
	}
	@fclose($fp);
	return true;
}

/**
 * 组合host port
 */
function construct_db_host($db_host, $db_port) {
	return $db_host . ':' . $db_port;
}

/**
 * 创建管理员帐号
 */
function create_admin_passport($admin_name, $admin_password, $admin_password2, $admin_email) {
	global $db, $err, $_LANG;
	if (admin_password === '') {
		$err->add($_LANG['password_empty_error']);
		return false;
	}

	/* 对密码的要求 大于等于8个字符，有数字 有字母*/
	if (!(strlen($admin_password) >= 8 && preg_match('/\d+/', $admin_password) && preg_match('/[a-zA-Z]+/', $admin_password))) {
		$err->add($_LANG['js_languages']['password_invaild']);
		return false;
	}

	/* 如果两次输入的密码不相等*/
	if ($admin_password !== $admin_password2) {
		$err->add($_LANG['password_not_eq']);
		return false;
	}

	require_once ROOT_PATH . '/data/config.php';
	require_once ROOT_PATH . '/includes/class.mysql.php';
	require_once ROOT_PATH . '/includes/comment.php';

	$db = MySQL::getInstance();
	$sql = 'INSET INTO `' . DB_PREFIX . 'users` (`name`,`password`,`nickname`,`email`)'
		. ' VALUES (\'' . $admin_name . '\', \'' . $admin_password . '\', \'' . $admin_name . '\', \'' . $admin_email . '\')';
	if (!$db->query($sql)) {
		$err->add($_LANG['create_password_failed']);
		return false;
	}
	return true;
}

/**
 * 取得当前的域名
 *
 * @access  public
 *
 * @return  string      当前的域名
 */
function get_domain() {
	/* 协议 */
	$protocol = http();

	/* 域名或IP地址 */
	if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
		$host = $_SERVER['HTTP_X_FORWARDED_HOST'];
	} elseif (isset($_SERVER['HTTP_HOST'])) {
		$host = $_SERVER['HTTP_HOST'];
	} else {
		/* 端口 */
		if (isset($_SERVER['SERVER_PORT'])) {
			$port = ':' . $_SERVER['SERVER_PORT'];

			if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)) {
				$port = '';
			}
		} else {
			$port = '';
		}

		if (isset($_SERVER['SERVER_NAME'])) {
			$host = $_SERVER['SERVER_NAME'] . $port;
		} elseif (isset($_SERVER['SERVER_ADDR'])) {
			$host = $_SERVER['SERVER_ADDR'] . $port;
		}
	}

	return $protocol . $host;
}


/**
 * 获得网站的根URL地址
 */
function cur_url() {
	if ($_SERVER['SERVER_PORT'] && $_SERVER['SERVER_PORT'] != 80) {
		$server_port = ':' . $_SERVER['SERVER_PORT'];
	} else {
		$server_port = '';
	}
	return 'http://'.$_SERVER['HTTP_HOST'] . $server_port;
}

/**
 * 获得 ECSHOP 当前环境的 URL 地址
 *
 * @access  public
 *
 * @return  void
 */
function root_url() {
	$PHP_SELF = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
	$ecserver = cur_url();
	$default_appurl = $ecserver.substr($PHP_SELF, 0, strpos($PHP_SELF, 'install/') - 1);

	return $default_appurl;
}

/**
 * 获得 ECSHOP 当前环境的 HTTP 协议方式
 *
 * @access  public
 *
 * @return  void
 */
function http() {
	return (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
}
